package com.itheima.test10;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:gy
 * @Date: 2025/09/04 17:14
 * @Description:
 */
public class Demo {
    public static void main(String[] args) throws Exception {
        //解析xml 将内容封装到学生对象中  将学生对象存到集合中
        //获取一个解析器对象
        SAXReader saxReader = new SAXReader();
        //利用这个解析器把xml文件加载到内存中,并返回一个文档对象
        Document document = saxReader.read(new File("Day14\\xml\\Student.xml"));
        //获取根标签 students
        Element rootElement = document.getRootElement();
        //通过根标签下所有的叫student的子标签
        List<Element> students = rootElement.elements("student");
        //System.out.println(student.size());
        //遍历集合  得到具体的student标签
        //定义一个存储学生对象的集合
        ArrayList<Student> al = new ArrayList<>();
        for (Element student : students) {
            //student就是每一个便签  获取id属性值
            Attribute id = student.attribute("id");
            //id的内容
            String idValue = id.getValue();
            //获取age 和  name标签
            Element name = student.element("name");
            Element age = student.element("age");
            //获取age和name标签的内容
            String nameText = name.getText();
            Integer ageText = Integer.parseInt(age.getText());
            Student student1 = new Student(nameText, ageText, idValue);
            al.add(student1);
        }
        //开始遍历了
        System.out.println("==========================================");
        for (Student student : al) {
            System.out.println(student);
        }
    }
}
